<template>
  <div class="login-page">
    <div class="login-card">
      <div class="brand"><div class="logo">OB</div><div class="name">注册账号</div></div>
      <form class="form" @submit.prevent="handleSubmit">
        <div class="form-item">
          <label>用户名</label>
          <input v-model.trim="form.username" type="text" placeholder="请输入用户名" required />
        </div>
        <div class="form-item">
          <label>邮箱</label>
          <input v-model.trim="form.email" type="email" placeholder="请输入邮箱" required />
        </div>
        <div class="form-item">
          <label>密码</label>
          <input v-model="form.password" type="password" placeholder="请输入密码" required />
        </div>
        <div class="form-item">
          <label>确认密码</label>
          <input v-model="form.confirmPassword" type="password" placeholder="请再次输入密码" required />
        </div>
        <div class="form-item form-inline">
          <label class="checkbox">
            <input type="checkbox" v-model="form.agree" /> 我已阅读并同意服务协议与隐私政策
          </label>
          <router-link to="/login" class="link">去登录</router-link>
        </div>
        <button class="btn btn-primary" type="submit" :disabled="loading">{{ loading ? '提交中...' : '注册' }}</button>
        <div class="tips">当前仅做前端演示，不调用后端接口</div>
      </form>
    </div>
  </div>
</template>

<script setup>
import { reactive, ref } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'

const router = useRouter()
const form = reactive({ username: '', email: '', password: '', confirmPassword: '', agree: true })
const loading = ref(false)

function validEmail(v){
  return /.+@.+\..+/.test(String(v||''))
}

async function handleSubmit(){
  if(!form.username || !form.email || !form.password || !form.confirmPassword) return
  if(!validEmail(form.email)) return ElMessage.warning('邮箱格式不正确')
  if(form.password !== form.confirmPassword) return ElMessage.error('两次输入的密码不一致')
  if(!form.agree) return ElMessage.warning('请先勾选同意协议')

  loading.value = true
  try{
    // 仅前端示例：模拟网络延迟
    await new Promise(r => setTimeout(r, 400))
    ElMessage.success('注册成功，请使用账号登录')
    const redirect = router.currentRoute.value.query.redirect
    router.replace({ path: '/login', query: redirect? { redirect: String(redirect) } : {} })
  }catch(e){
    ElMessage.error('注册失败，请重试')
  }finally{ loading.value = false }
}
</script>

<style scoped>
@import '@/assets/auth.css';
</style>

